package com.esms.controller;

import com.esms.po.Employee;
import com.esms.po.LogValue;
import com.esms.po.MenuPerm;
import com.esms.po.SystemManager;
import com.esms.service.DepartmentService;
import com.esms.service.ILogService;
import com.esms.service.LoginMenuPermService;
import com.esms.service.impl.LoginServiceImpl;
import com.esms.utils.CaptchaUtil;
import com.esms.utils.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: admin
 * @Description: 管理员和员工登陆控制
 * @Date: 14:33 2021/10/5
 **/
@Controller
public class LoginController {
    @Autowired
    public DepartmentService departmentService;
    @Autowired
    public ILogService ILogService;
    @Autowired
    private LoginServiceImpl loginService = null;
    @Autowired
    private LoginMenuPermService loginMenuPermService;


    /**
     * @Author: admin
     * @Description: 验证码变更
     * @Date: 14:33 2021/10/5
     * @Param: [request, response]
     * @Return: void
     **/
    @RequestMapping(value = "/changeCode.do")
    @ResponseBody
    public void getIdentifyingCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 验证码存储在session的identifyingCode，属性中
        CaptchaUtil.outputCaptcha(request, response);
    }

    // 获取员工登陆界面
    @RequestMapping("/")
    public String getLoginPage() {
        return "employee/login.html";
    }

    // 获取管理员登陆界面
    @RequestMapping("/admin.do")
    public String getAdminLoginPage(HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("/");
        request.getSession().setAttribute("realPath", realPath);
        return "admin/adminLogin.html";
    }


    /**
     * 员工登录操作
     *
     * @param httpSession
     * @param username
     * @param password
     * @param identifyingcode
     * @return
     */
    @RequestMapping(value = "/employeeLogin.do")
    @ResponseBody
    public Message employeeLogin(HttpSession httpSession, String username,
                                 String password, String identifyingcode) {

        Timestamp date = new Timestamp(new Date().getTime());
        String method = "employeeLogin";
        if (loginService.checkWhetherLimitForMoreThanFiveTimes(username)) {
            return Message.error(new String("已经五次密码错误,请联系管理员".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        }
        if (StringUtils.isEmpty(username)) {
            return Message.error(new String("请填写工号".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        }
        if (StringUtils.isEmpty(password)) {
            return Message.error("请填写密码");
        }
        if (StringUtils.isEmpty(identifyingcode)) {
            return Message.error("请填写验证码");
        }
        String code = (String) httpSession.getAttribute("identifyingCode");
        if (!identifyingcode.equalsIgnoreCase(code)) {
            //记录登录成功日志
            String value = "工号" + username + "员工，于" + date + "登录失败：验证码错误!";
            insertLogRecord(username, value, date, method);
            return Message.error("验证码错误");
        }
        try {
            Employee employee = loginService.findEmployeeByIdAndPassword(username, password);
            if (employee == null) {
                //记录登录成功日志
                String value = "工号" + username + "员工，于" + date + "登录失败：工号或密码错误!";
                Integer current = loginService.toIncreaseNumberWrong(username);
                insertLogRecord(username, value, date, method);
                if (current != 0) {
                    return Message.error("工号或密码错误,当前用户连续错误次数:" + current);
                } else {
                    return Message.error("工号或密码错误");
                }

            }
            httpSession.setAttribute("employeeId", employee.geteId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (loginService.resetErrNumAndCheck90Day(username)) {
            return Message.error("90天未更新新密码,禁止登陆,请联系管理员");
        }
        //记录登录成功日志
        String value = "工号" + username + "员工，于" + date + "成功登录系统!";
        insertLogRecord(username, value, date, method);

        return Message.success("员工登录成功");
    }

    /**
     * 登录日志记录操作
     **/
    public void insertLogRecord(String account, String value, Timestamp date, String method) {
        LogValue record = new LogValue();
        record.setLogAccount(account);
        record.setLogClass(this.getClass().getName());
        record.setLogMethod(method);
        record.setLogValue(value);
        record.setCreateTime(date);
        record.setUpdateTime(date);
        ILogService.insert(record);
    }

    @RequestMapping(value = "/loginSuccess.do")
    public String loginSucceses(Model model) throws Exception {
        return "employee/index.html";
    }

    /**
     * 管理员登录操作
     *
     * @param httpSession
     * @param username
     * @param password
     * @param identifyingcode
     * @return
     */
    @RequestMapping(value = "/adminLogin.do")
    @ResponseBody
    public Message adminLogin(HttpSession httpSession, String username,
                              String password, String identifyingcode) {

        Timestamp date = new Timestamp(new Date().getTime());
        String method = "adminLogin";

        if (StringUtils.isEmpty(username)) {
            return Message.error("请填写账号");
        }
        if (StringUtils.isEmpty(password)) {
            return Message.error("请填写密码");
        }
        if (StringUtils.isEmpty(identifyingcode)) {
            return Message.error("请填写验证码");
        }
        String code = (String) httpSession.getAttribute("identifyingCode");
        if (identifyingcode.equalsIgnoreCase(code)) {
            SystemManager manager = loginService.findSystemManagerByIdAndPassword(username, password);
            if (manager == null) {
                return Message.error("账号或密码错误");
            }
            // 保存到session
            httpSession.setAttribute("admin", manager);
            //记录登录成功日志
            String value = "工号" + username + "员工，于" + date + "成功登录系统!";
            insertLogRecord(username, value, date, method);
            return Message.success("登录成功");
        } else {
            //记录登录成功日志
            String value = "工号" + username + "员工，于" + date + "登录失败：验证码错误!";
            insertLogRecord(username, value, date, method);
            return Message.error("验证码错误");
        }
    }

    @RequestMapping(value = "/getAdminAccount.do")
    @ResponseBody
    public String getAdminAccount(HttpSession httpSession) {
        SystemManager systemManager = (SystemManager) httpSession.getAttribute("admin");
//        SystemManager manager = loginService.findSystemManagerById(id);
        return systemManager.getSmAccount();
    }

    @RequestMapping(value = "/getEmployeeAccount.do")
    @ResponseBody
    public Map<String, String> getEmployeeAccount(HttpSession httpSession) {
        Integer id = (Integer) httpSession.getAttribute("employeeId");
        Employee employee = loginService.findEmployeeById(id);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("account", employee.geteAccount());
        map.put("name", employee.geteName());
        return map;
    }

    /**
     * 查看哪些工号可以查看考核结果
     **/
    @RequestMapping(value = "/getShowMenuPermAccount.do")
    @ResponseBody
    public Map<String, String> getShowMenuPermAccount(HttpSession httpSession, String menuFlag) {

        String flag = "N";
        Integer id = (Integer) httpSession.getAttribute("employeeId");
        Employee employee = loginService.findEmployeeById(id);
        String currAccount = employee.geteAccount();
//        MenuPerm menuPerm = new MenuPerm();
//        try {
//            menuPerm = loginMenuPermService.selectShowMenuPermAccountByFlag(menuFlag);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String showAccount = menuPerm.getMenuAccount();
//        if (showAccount.contains(currAccount)) {
//            flag = "Y";
//        }
        if (loginMenuPermService.whetherHasMenu(menuFlag, currAccount)) {
            flag = "Y";
        }
        HashMap<String, String> map = new HashMap<String, String>();

        map.put("flag", flag);
        return map;
    }


    @RequestMapping(value = "/logout.do")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute("employeeId");
        return "redirect:/";
    }

    @RequestMapping(value = "/logoutAdmin.do")
    public String logoutAdmin(HttpSession httpSession) {
        httpSession.removeAttribute("admin");
        return "redirect:/admin.do";
    }
}
